package com.yserp.kp.controller;
import com.yserp.kp.entity.TKpYushouHEntity;
import com.yserp.kp.service.TKpYushouHServiceI;
import com.yserp.kp.page.TKpYushouHPage;
import com.yserp.kp.entity.TKpYushouEntity;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yserp.kpmd.entity.TKpCusEntity;
import com.yserp.kpmd.entity.TKpGongdiEntity;
import org.apache.log4j.Logger;
import org.jeecgframework.core.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.springframework.ui.ModelMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.jeecgframework.jwt.util.GsonUtil;
import org.jeecgframework.jwt.util.ResponseMessage;
import org.jeecgframework.jwt.util.Result;
import com.alibaba.fastjson.JSONArray;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.jeecgframework.core.beanvalidator.BeanValidators;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.net.URI;
import org.springframework.http.MediaType;
import org.springframework.web.util.UriComponentsBuilder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**   
 * @Title: Controller
 * @Description: 收款单
 * @author onlineGenerator
 * @date 2018-08-02 03:31:58
 * @version V1.0   
 *
 */
@Api(value="TKpYushouH",description="收款单",tags="tKpYushouHController")
@Controller
@RequestMapping("/tKpYushouHController")
public class TKpYushouHController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(TKpYushouHController.class);

	@Autowired
	private TKpYushouHServiceI tKpYushouHService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private Validator validator;

	/**
	 * 收款单列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("com/yserp/kp/tKpYushouHList");
	}

	@RequestMapping(params = "listtk")
	public ModelAndView listtk(HttpServletRequest request) {
		return new ModelAndView("com/yserp/kp/tKpYushouHtkList");
	}


	@RequestMapping(params = "listsx")
	public ModelAndView listsx(HttpServletRequest request) {
		return new ModelAndView("com/yserp/kp/tKpYushouHsxList");
	}


	/**
	 * 预收管理列表 页面跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "doPrint")
	public ModelAndView doPrint(String id,HttpServletRequest request) {
		TKpYushouHEntity t = tKpYushouHService.get(TKpYushouHEntity.class, Integer.parseInt(id));
		request.setAttribute("kprq",DateUtils.date2Str(t.getCreateDate(),DateUtils.date_sdf));
		try{
			request.setAttribute("jinedx",number2cn.number2CNMontrayUnit(new BigDecimal(t.getSkAmount())));

		}catch (Exception e){

		}
		request.setAttribute("tKpYushouPage", t);


		//===================================================================================
		//获取参数
		Object id0 = t.getSkid();
		//===================================================================================
		//查询-收款行项目
		String hql0 = "from TKpYushouEntity where 1 = 1 AND sKID = ? ";
		try{
			List<TKpYushouEntity> tKpYushouEntityList = systemService.findHql(hql0,id0);
			request.setAttribute("tKpYushouList", tKpYushouEntityList);
		}catch(Exception e){
			logger.info(e.getMessage());
		}

		return new ModelAndView("com/yserp/kp/kpyushou-print");
	}
	@RequestMapping(params = "doPrinttk")
	public ModelAndView doPrinttk(String id,HttpServletRequest request) {
		TKpYushouHEntity t = tKpYushouHService.get(TKpYushouHEntity.class, Integer.parseInt(id));
		request.setAttribute("kprq",DateUtils.date2Str(t.getCreateDate(),DateUtils.date_sdf));
		try{
			request.setAttribute("jinedx",number2cn.number2CNMontrayUnit(new BigDecimal(t.getSkAmount())));

		}catch (Exception e){

		}
		request.setAttribute("tKpYushouPage", t);


		//===================================================================================
		//获取参数
		Object id0 = t.getSkid();
		//===================================================================================
		//查询-收款行项目
		String hql0 = "from TKpYushouEntity where 1 = 1 AND sKID = ? ";
		try{
			List<TKpYushouEntity> tKpYushouEntityList = systemService.findHql(hql0,id0);
			request.setAttribute("tKpYushouList", tKpYushouEntityList);
		}catch(Exception e){
			logger.info(e.getMessage());
		}

		return new ModelAndView("com/yserp/kp/kpyushoutk-print");
	}
	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(String ysType,TKpYushouHEntity tKpYushouH,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(TKpYushouHEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tKpYushouH);
		try{
		//自定义追加查询条件
		String query_createDate_begin = request.getParameter("createDate_begin");
		String query_createDate_end = request.getParameter("createDate_end");
		if(StringUtil.isNotEmpty(query_createDate_begin)){
			cq.ge("createDate", new SimpleDateFormat("yyyy-MM-dd").parse(query_createDate_begin));
		}
		if(StringUtil.isNotEmpty(query_createDate_end)){
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar c = Calendar.getInstance();
			c.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(query_createDate_end));
			c.add(Calendar.DAY_OF_MONTH, 1);
			cq.le("createDate", DateUtils.str2Date(sf.format(c.getTime()),DateUtils.date_sdf));
		}
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.tKpYushouHService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除收款单
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(TKpYushouHEntity tKpYushouH, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		tKpYushouH = systemService.getEntity(TKpYushouHEntity.class, tKpYushouH.getId());
		String message = "收款单删除成功";
		try{
			tKpYushouHService.delMain(tKpYushouH);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "收款单删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 批量删除收款单
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		String message = "收款单删除成功";
		try{
			for(String id:ids.split(",")){
				TKpYushouHEntity tKpYushouH = systemService.getEntity(TKpYushouHEntity.class,
				Integer.parseInt(id)
				);
				tKpYushouHService.delMain(tKpYushouH);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "收款单删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 添加收款单
	 * 
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(TKpYushouHEntity tKpYushouH,TKpYushouHPage tKpYushouHPage, HttpServletRequest request) {
		List<TKpYushouEntity> tKpYushouList =  tKpYushouHPage.getTKpYushouList();
		AjaxJson j = new AjaxJson();
		String message = "添加成功";
		try{

			TKpCusEntity cusEntity = systemService.findUniqueByProperty(TKpCusEntity.class,"cusCode",tKpYushouH.getCusCode());
			if(cusEntity!=null){
				tKpYushouH.setCusName(cusEntity.getCusName());
			}
			TKpGongdiEntity kpGongdiEntity = systemService.findUniqueByProperty(TKpGongdiEntity.class,"gdCode",tKpYushouH.getGdCode());
			if(kpGongdiEntity!=null){
				tKpYushouH.setGdName(kpGongdiEntity.getGdName()); ;
			}
			Map<String, Object> countMap = systemService
					.findOneForJdbc("SELECT max(skid) as count FROM t_kp_yushou_h  t where  date_format(t.create_date,'%Y-%m') = date_format(NOW(),'%Y-%m');");
			String noticeid = null;
			if (countMap != null) {
//				String temp = countMap.get("count").toString();

				String temp=null;
				try{
					temp = countMap.get("count").toString();

				}catch (Exception e){
					temp = "0000";
				}

				Long templ = Long.parseLong(temp.substring(temp.length()-4,temp.length()));
				templ = templ + 1;
						noticeid =  DateUtils.date2Str(new Date(), DateUtils.date_sdfyymm)
						+ StringUtil.leftPad(
						templ.intValue(), 4,
						'0');
			}
			try{
				Double sum = 0.00;
				for(TKpYushouEntity t:tKpYushouList){
					if(StringUtil.isNotEmpty(t.getYsJine())) {
						sum = sum + Double.parseDouble(t.getYsJine());
					}
				}
				if("退款".equals(tKpYushouH.getYsType())){
					sum=0-Math.abs(sum);
				}
				DecimalFormat df   = new DecimalFormat("######0.00");
				tKpYushouH.setSkAmount(df.format(sum));
			}catch (Exception  e){

			}
			tKpYushouH.setSkid(noticeid);
			tKpYushouHService.addMain(tKpYushouH, tKpYushouList);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "收款单添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	/**
	 * 更新收款单
	 * 
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(TKpYushouHEntity tKpYushouH,TKpYushouHPage tKpYushouHPage, HttpServletRequest request) {
		List<TKpYushouEntity> tKpYushouList =  tKpYushouHPage.getTKpYushouList();
		AjaxJson j = new AjaxJson();
		String message = "更新成功";
		try{
			tKpYushouHService.updateMain(tKpYushouH, tKpYushouList);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "更新收款单失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}


	/**
	 * 更新预收管理
	 *
	 * @return
	 */
	@RequestMapping(params = "doUpdatesp")
	@ResponseBody
	public AjaxJson doUpdatesp(String id,String bpmStatus, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "成功";
		TKpYushouHEntity t = tKpYushouHService.get(TKpYushouHEntity.class, Integer.parseInt(request.getParameter("id")));
		try {
			t.setBpmStatus(request.getParameter("bpmStatus"));
			tKpYushouHService.saveOrUpdate(t);


			//===================================================================================
			//获取参数
			Object id0 = t.getSkid();
			//===================================================================================
			//查询-收款行项目
			String hql0 = "from TKpYushouEntity where 1 = 1 AND sKID = ? ";
			try{
				List<TKpYushouEntity> tKpYushouEntityList = systemService.findHql(hql0,id0);
				for(TKpYushouEntity  tyushou:tKpYushouEntityList){
					tyushou.setBpmStatus(t.getBpmStatus());
					systemService.updateEntitie(tyushou);
				}
			}catch(Exception e){
				logger.info(e.getMessage());
			}

			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 收款单新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(String ysType,TKpYushouHEntity tKpYushouH, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(tKpYushouH.getId())) {
			tKpYushouH = tKpYushouHService.getEntity(TKpYushouHEntity.class, tKpYushouH.getId());
			req.setAttribute("tKpYushouHPage", tKpYushouH);
		}
		req.setAttribute("ysType",ysType);

		return new ModelAndView("com/yserp/kp/tKpYushouH-add");
	}
	
	/**
	 * 收款单编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(TKpYushouHEntity tKpYushouH, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(tKpYushouH.getId())) {
			tKpYushouH = tKpYushouHService.getEntity(TKpYushouHEntity.class, tKpYushouH.getId());
			req.setAttribute("tKpYushouHPage", tKpYushouH);
		}
		return new ModelAndView("com/yserp/kp/tKpYushouH-update");
	}
	
	
	/**
	 * 加载明细列表[收款行项目]
	 * 
	 * @return
	 */
	@RequestMapping(params = "tKpYushouList")
	public ModelAndView tKpYushouList(TKpYushouHEntity tKpYushouH, HttpServletRequest req) {
	
		//===================================================================================
		//获取参数
		Object id0 = tKpYushouH.getSkid();
		//===================================================================================
		//查询-收款行项目
	    String hql0 = "from TKpYushouEntity where 1 = 1 AND sKID = ? ";
	    try{
	    	List<TKpYushouEntity> tKpYushouEntityList = systemService.findHql(hql0,id0);
			req.setAttribute("tKpYushouList", tKpYushouEntityList);
		}catch(Exception e){
			logger.info(e.getMessage());
		}
		return new ModelAndView("com/yserp/kp/tKpYushouList");
	}

    /**
    * 导出excel
    *
    * @param request
    * @param response
    */
    @RequestMapping(params = "exportXls")
    public String exportXls(TKpYushouHEntity tKpYushouH,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid,ModelMap map) {
    	CriteriaQuery cq = new CriteriaQuery(TKpYushouHEntity.class, dataGrid);
    	//查询条件组装器
    	org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tKpYushouH);
    	try{
    	//自定义追加查询条件
    	}catch (Exception e) {
    		throw new BusinessException(e.getMessage());
    	}
    	cq.add();
    	List<TKpYushouHEntity> list=this.tKpYushouHService.getListByCriteriaQuery(cq, false);
    	List<TKpYushouHPage> pageList=new ArrayList<TKpYushouHPage>();
        if(list!=null&&list.size()>0){
        	for(TKpYushouHEntity entity:list){
        		try{
        		TKpYushouHPage page=new TKpYushouHPage();
        		   MyBeanUtils.copyBeanNotNull2Bean(entity,page);
            	    Object id0 = entity.getSkid();
				    String hql0 = "from TKpYushouEntity where 1 = 1 AND sKID = ? ";
        	        List<TKpYushouEntity> tKpYushouEntityList = systemService.findHql(hql0,id0);
            		page.setTKpYushouList(tKpYushouEntityList);
            		pageList.add(page);
            	}catch(Exception e){
            		logger.info(e.getMessage());
            	}
            }
        }
        map.put(NormalExcelConstants.FILE_NAME,"收款单");
        map.put(NormalExcelConstants.CLASS,TKpYushouHPage.class);
        map.put(NormalExcelConstants.PARAMS,new ExportParams("收款单列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
            "导出信息"));
        map.put(NormalExcelConstants.DATA_LIST,pageList);
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}

    /**
	 * 通过excel导入数据
	 * @param request
	 * @param
	 * @return
	 */
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(2);
			params.setNeedSave(true);
			try {
				List<TKpYushouHPage> list =  ExcelImportUtil.importExcel(file.getInputStream(), TKpYushouHPage.class, params);
				TKpYushouHEntity entity1=null;
				for (TKpYushouHPage page : list) {
					entity1=new TKpYushouHEntity();
					MyBeanUtils.copyBeanNotNull2Bean(page,entity1);
		            tKpYushouHService.addMain(entity1, page.getTKpYushouList());
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(ExceptionUtil.getExceptionMessage(e));
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			}
			return j;
	}
	/**
	* 导出excel 使模板
	*/
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(ModelMap map) {
		map.put(NormalExcelConstants.FILE_NAME,"收款单");
		map.put(NormalExcelConstants.CLASS,TKpYushouHPage.class);
		map.put(NormalExcelConstants.PARAMS,new ExportParams("收款单列表", "导出人:"+ ResourceUtil.getSessionUser().getRealName(),
		"导出信息"));
		map.put(NormalExcelConstants.DATA_LIST,new ArrayList());
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	* 导入功能跳转
	*
	* @return
	*/
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name", "tKpYushouHController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}

 	
 	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="收款单列表信息",produces="application/json",httpMethod="GET")
	public ResponseMessage<List<TKpYushouHPage>> list() {
		List<TKpYushouHEntity> list= tKpYushouHService.getList(TKpYushouHEntity.class);
    	List<TKpYushouHPage> pageList=new ArrayList<TKpYushouHPage>();
        if(list!=null&&list.size()>0){
        	for(TKpYushouHEntity entity:list){
        		try{
        			TKpYushouHPage page=new TKpYushouHPage();
        		   MyBeanUtils.copyBeanNotNull2Bean(entity,page);
					Object id0 = entity.getSkid();
				     String hql0 = "from TKpYushouEntity where 1 = 1 AND sKID = ? ";
	    			List<TKpYushouEntity> tKpYushouOldList = this.tKpYushouHService.findHql(hql0,id0);
            		page.setTKpYushouList(tKpYushouOldList);
            		pageList.add(page);
            	}catch(Exception e){
            		logger.info(e.getMessage());
            	}
            }
        }
		return Result.success(pageList);
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="根据ID获取收款单信息",notes="根据ID获取收款单信息",httpMethod="GET",produces="application/json")
	public ResponseMessage<?> get(@ApiParam(required=true,name="id",value="ID")@PathVariable("id") String id) {
		TKpYushouHEntity task = tKpYushouHService.get(TKpYushouHEntity.class, id);
		if (task == null) {
			return Result.error("根据ID获取收款单信息为空");
		}
		TKpYushouHPage page = new TKpYushouHPage();
		try {
			MyBeanUtils.copyBeanNotNull2Bean(task, page);
				Object id0 = task.getSkid();
		    String hql0 = "from TKpYushouEntity where 1 = 1 AND sKID = ? ";
			List<TKpYushouEntity> tKpYushouOldList = this.tKpYushouHService.findHql(hql0,id0);
    		page.setTKpYushouList(tKpYushouOldList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Result.success(page);
	}
 	
 	@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value="创建收款单")
	public ResponseMessage<?> create(@ApiParam(name="收款单对象")@RequestBody TKpYushouHPage tKpYushouHPage, UriComponentsBuilder uriBuilder) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<TKpYushouHPage>> failures = validator.validate(tKpYushouHPage);
		if (!failures.isEmpty()) {
			return Result.error(JSONArray.toJSONString(BeanValidators.extractPropertyAndMessage(failures)));
		}

		//保存
		List<TKpYushouEntity> tKpYushouList =  tKpYushouHPage.getTKpYushouList();
		
		TKpYushouHEntity tKpYushouH = new TKpYushouHEntity();
		try{
			MyBeanUtils.copyBeanNotNull2Bean(tKpYushouHPage,tKpYushouH);
		}catch(Exception e){
            logger.info(e.getMessage());
            return Result.error("保存收款单失败");
        }
		tKpYushouHService.addMain(tKpYushouH, tKpYushouList);

		return Result.success(tKpYushouH);
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value="更新收款单",notes="更新收款单")
	public ResponseMessage<?> update(@RequestBody TKpYushouHPage tKpYushouHPage) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<TKpYushouHPage>> failures = validator.validate(tKpYushouHPage);
		if (!failures.isEmpty()) {
			return Result.error(JSONArray.toJSONString(BeanValidators.extractPropertyAndMessage(failures)));
		}

		//保存
		List<TKpYushouEntity> tKpYushouList =  tKpYushouHPage.getTKpYushouList();
		
		TKpYushouHEntity tKpYushouH = new TKpYushouHEntity();
		try{
			MyBeanUtils.copyBeanNotNull2Bean(tKpYushouHPage,tKpYushouH);
		}catch(Exception e){
            logger.info(e.getMessage());
            return Result.error("收款单更新失败");
        }
		tKpYushouHService.updateMain(tKpYushouH, tKpYushouList);

		//按Restful约定，返回204状态码, 无内容. 也可以返回200状态码.
		return Result.success();
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ResponseStatus(HttpStatus.NO_CONTENT)
	@ApiOperation(value="删除收款单")
	public ResponseMessage<?> delete(@ApiParam(name="id",value="ID",required=true)@PathVariable("id") String id) {
		logger.info("delete[{}]" + id);
		// 验证
		if (StringUtils.isEmpty(id)) {
			return Result.error("ID不能为空");
		}
		try {
			TKpYushouHEntity tKpYushouH = tKpYushouHService.get(TKpYushouHEntity.class, id);
			tKpYushouHService.delMain(tKpYushouH);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("收款单删除失败");
		}

		return Result.success();
	}
}
